<template>
  <dynamic-table ref="tableRef" :columns="columns" :page-option="{ departmentid }" :get-list-func="getClientListWithStatus" rowKey="id" :row-selection="rowSelection">
    <template v-slot:title>
      <a-button @click="accountManage" :disabled="rowSelection.selectedRowKeys.length == 0" type="primary">
        账号管理
      </a-button>
    </template>
  </dynamic-table>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, watch, computed, nextTick, ref } from 'vue'
import DynamicTable from '@/components/dynamic-table.vue'
import { useCreateModal } from '@/hooks'
import { clientGetByDepartment, ClientOnlineList } from '@/api/client'
import AddModal from '@/views/terminal/add-modal.vue'
import { formatDate } from '@/utils/common'
import { columns } from '@/views/terminal/columns'

export default defineComponent({
  name: 'terminal-list',
  components: {
    DynamicTable
  },
  props: ['departmentid'],
  setup(props) {
    const tableRef = ref<any>(null)

    const state = reactive({
      data: [],
      uploading: false,
      tableLoading: false,
      rowSelection: {
        hideDefaultSelections: true,
        onChange: (selectedRowKeys, selectedRows) => {
          state.rowSelection.selectedRowKeys = selectedRowKeys.slice(-1)
          state.rowSelection.selectedRows = selectedRows.slice(-1)
        },
        selectedRowKeys: [],
        selectedRows: []
      }
    })

    const getClientListWithStatus = async params => {
      const data = (await clientGetByDepartment(params)) as Map<number, object>
      const list = (await ClientOnlineList()) as Array<string>
      Object.values(data['data'] as object).forEach(item => {
        if (list.includes(item['clienthash'])) {
          item['status'] = 1
        } else {
          item['status'] = 0
        }
      })
      console.log('data back', data)
      return data
    }

    watch(
      () => props.departmentid,
      () => {
        state.rowSelection.selectedRowKeys = []
        nextTick(() => tableRef.value.refreshTableData())
      }
    )

    // 账号管理
    const accountManage = () => {
      useCreateModal(AddModal, {
        clienthash: state.rowSelection.selectedRows[0]['clienthash'],
        callback: () => {
          tableRef.value.refreshTableData()
        }
      })
    }

    return {
      ...toRefs(state),
      columns,
      accountManage,
      tableRef,
      formatDate,
      getClientListWithStatus
    }
  }
})
</script>
